import 'package:flutter_test/flutter_test.dart';
import 'package:ghpfc_fmp/models/carbon_footprint_record.dart';
import 'package:ghpfc_fmp/services/carbon_footprint_service.dart';
import 'package:ghpfc_fmp/core/database_helper.dart';

void main() {
  group('CarbonFootprintRecord Model Tests', () {
    test('should create CarbonFootprintRecord from map', () {
      final map = {
        'id': 1,
        'record_code': 'CFP-20241201-001',
        'record_name': '测试记录',
        'process_type': 1,
        'production_capacity': 1000.0,
        'energy_consumption': 50000.0,
        'carbon_emission': 0.0,
        'energy_source': '太阳能',
        'equipment_efficiency': 85.5,
        'operation_hours': 8760,
        'location': '北京',
        'project_phase': '运行阶段',
        'record_date': '2024-12-01',
        'description': '测试描述',
        'created_by': 1,
        'created_at': '2024-12-01T10:00:00.000Z',
        'updated_at': '2024-12-01T10:00:00.000Z',
        'is_deleted': 0,
      };

      final record = CarbonFootprintRecord.fromMap(map);

      expect(record.id, 1);
      expect(record.recordCode, 'CFP-20241201-001');
      expect(record.recordName, '测试记录');
      expect(record.processType, 1);
      expect(record.processTypeName, '电解水制氢');
      expect(record.productionCapacity, 1000.0);
      expect(record.energyConsumption, 50000.0);
      expect(record.carbonEmission, 0.0);
      expect(record.energySource, '太阳能');
      expect(record.equipmentEfficiency, 85.5);
      expect(record.operationHours, 8760);
      expect(record.location, '北京');
      expect(record.projectPhase, '运行阶段');
      expect(record.isDeleted, false);
    });

    test('should convert CarbonFootprintRecord to map', () {
      final record = CarbonFootprintRecord(
        id: 1,
        recordCode: 'CFP-20241201-001',
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        energySource: '太阳能',
        equipmentEfficiency: 85.5,
        operationHours: 8760,
        location: '北京',
        projectPhase: '运行阶段',
        recordDate: DateTime(2024, 12, 1),
        description: '测试描述',
        createdBy: 1,
        createdAt: DateTime(2024, 12, 1, 10, 0, 0),
        updatedAt: DateTime(2024, 12, 1, 10, 0, 0),
        isDeleted: false,
      );

      final map = record.toMap();

      expect(map['id'], 1);
      expect(map['record_code'], 'CFP-20241201-001');
      expect(map['record_name'], '测试记录');
      expect(map['process_type'], 1);
      expect(map['production_capacity'], 1000.0);
      expect(map['energy_consumption'], 50000.0);
      expect(map['carbon_emission'], 0.0);
      expect(map['energy_source'], '太阳能');
      expect(map['equipment_efficiency'], 85.5);
      expect(map['operation_hours'], 8760);
      expect(map['location'], '北京');
      expect(map['project_phase'], '运行阶段');
      expect(map['is_deleted'], 0);
    });

    test('should calculate emission intensity correctly', () {
      final record = CarbonFootprintRecord(
        recordCode: 'CFP-20241201-001',
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 500.0,
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      expect(record.emissionIntensity, 0.5); // 500/1000 = 0.5
    });

    test('should calculate energy intensity correctly', () {
      final record = CarbonFootprintRecord(
        recordCode: 'CFP-20241201-001',
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 500.0,
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      expect(record.energyIntensity, 50.0); // 50000/1000 = 50
    });

    test('should return zero intensity for zero production capacity', () {
      final record = CarbonFootprintRecord(
        recordCode: 'CFP-20241201-001',
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 0.0,
        energyConsumption: 50000.0,
        carbonEmission: 500.0,
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      expect(record.emissionIntensity, 0.0);
      expect(record.energyIntensity, 0.0);
    });
  });

  group('CarbonFootprintRecord Validation Tests', () {
    test('should validate record name correctly', () {
      expect(CarbonFootprintRecord.validateRecordName(null), '记录名称不能为空');
      expect(CarbonFootprintRecord.validateRecordName(''), '记录名称不能为空');
      expect(CarbonFootprintRecord.validateRecordName('a'), '记录名称至少2个字符');
      expect(CarbonFootprintRecord.validateRecordName('ab'), null);
      expect(CarbonFootprintRecord.validateRecordName('a' * 201), '记录名称不能超过200个字符');
    });

    test('should validate production capacity correctly', () {
      expect(CarbonFootprintRecord.validateProductionCapacity(null), '产能不能为空');
      expect(CarbonFootprintRecord.validateProductionCapacity(''), '产能不能为空');
      expect(CarbonFootprintRecord.validateProductionCapacity('abc'), '产能必须是数字');
      expect(CarbonFootprintRecord.validateProductionCapacity('0'), '产能不能小于0.01');
      expect(CarbonFootprintRecord.validateProductionCapacity('0.005'), '产能不能小于0.01');
      expect(CarbonFootprintRecord.validateProductionCapacity('1000001'), '产能不能超过1,000,000');
      expect(CarbonFootprintRecord.validateProductionCapacity('1000'), null);
    });

    test('should validate energy consumption correctly', () {
      expect(CarbonFootprintRecord.validateEnergyConsumption(null), '能耗不能为空');
      expect(CarbonFootprintRecord.validateEnergyConsumption(''), '能耗不能为空');
      expect(CarbonFootprintRecord.validateEnergyConsumption('abc'), '能耗必须是数字');
      expect(CarbonFootprintRecord.validateEnergyConsumption('-1'), '能耗不能小于0');
      expect(CarbonFootprintRecord.validateEnergyConsumption('1000001'), '能耗不能超过1,000,000');
      expect(CarbonFootprintRecord.validateEnergyConsumption('50000'), null);
    });

    test('should validate carbon emission correctly', () {
      expect(CarbonFootprintRecord.validateCarbonEmission(null), '碳排放量不能为空');
      expect(CarbonFootprintRecord.validateCarbonEmission(''), '碳排放量不能为空');
      expect(CarbonFootprintRecord.validateCarbonEmission('abc'), '碳排放量必须是数字');
      expect(CarbonFootprintRecord.validateCarbonEmission('-1'), '碳排放量不能小于0');
      expect(CarbonFootprintRecord.validateCarbonEmission('1001'), '碳排放量不能超过1,000');
      expect(CarbonFootprintRecord.validateCarbonEmission('500'), null);
    });

    test('should validate equipment efficiency correctly', () {
      expect(CarbonFootprintRecord.validateEquipmentEfficiency(null), null); // 可选字段
      expect(CarbonFootprintRecord.validateEquipmentEfficiency(''), null); // 可选字段
      expect(CarbonFootprintRecord.validateEquipmentEfficiency('abc'), '设备效率必须是数字');
      expect(CarbonFootprintRecord.validateEquipmentEfficiency('-1'), '设备效率必须在0-100之间');
      expect(CarbonFootprintRecord.validateEquipmentEfficiency('101'), '设备效率必须在0-100之间');
      expect(CarbonFootprintRecord.validateEquipmentEfficiency('85.5'), null);
    });

    test('should validate operation hours correctly', () {
      expect(CarbonFootprintRecord.validateOperationHours(null), null); // 可选字段
      expect(CarbonFootprintRecord.validateOperationHours(''), null); // 可选字段
      expect(CarbonFootprintRecord.validateOperationHours('abc'), '运行时间必须是整数');
      expect(CarbonFootprintRecord.validateOperationHours('-1'), '运行时间必须在0-8760之间');
      expect(CarbonFootprintRecord.validateOperationHours('8761'), '运行时间必须在0-8760之间');
      expect(CarbonFootprintRecord.validateOperationHours('8760'), null);
    });

    test('should validate process type correctly', () {
      expect(CarbonFootprintRecord.validateProcessType(null), '工艺类型不能为空');
      expect(CarbonFootprintRecord.validateProcessType(0), '工艺类型选择无效');
      expect(CarbonFootprintRecord.validateProcessType(5), '工艺类型选择无效');
      expect(CarbonFootprintRecord.validateProcessType(1), null);
      expect(CarbonFootprintRecord.validateProcessType(2), null);
      expect(CarbonFootprintRecord.validateProcessType(3), null);
      expect(CarbonFootprintRecord.validateProcessType(4), null);
    });
  });

  group('CarbonFootprintService Tests', () {
    late CarbonFootprintService service;

    setUpAll(() async {
      // 初始化数据库
      await DatabaseHelper.initializeDatabaseFactory();
      final dbHelper = DatabaseHelper();
      await dbHelper.database;
    });

    setUp(() {
      service = CarbonFootprintService();
    });

    test('should create carbon footprint record', () async {
      final record = CarbonFootprintRecord(
        recordCode: '', // 将由服务生成
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        energySource: '太阳能',
        equipmentEfficiency: 85.5,
        operationHours: 8760,
        location: '北京',
        projectPhase: '运行阶段',
        recordDate: DateTime.now(),
        description: '测试描述',
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      final createdRecord = await service.createRecord(record);

      expect(createdRecord.id, isNotNull);
      expect(createdRecord.recordCode, isNotEmpty);
      expect(createdRecord.recordName, '测试记录');
      expect(createdRecord.processType, 1);
      expect(createdRecord.processTypeName, '电解水制氢');
    });

    test('should get all records', () async {
      final records = await service.getAllRecords();

      expect(records, isA<List<CarbonFootprintRecord>>());
      expect(records.length, greaterThanOrEqualTo(0));
    });

    test('should get record by id', () async {
      // 先创建一个记录
      final record = CarbonFootprintRecord(
        recordCode: '',
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      final createdRecord = await service.createRecord(record);
      final retrievedRecord = await service.getRecordById(createdRecord.id!);

      expect(retrievedRecord, isNotNull);
      expect(retrievedRecord!.id, createdRecord.id);
      expect(retrievedRecord.recordName, createdRecord.recordName);
    });

    test('should update record', () async {
      // 先创建一个记录
      final record = CarbonFootprintRecord(
        recordCode: '',
        recordName: '原始记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      final createdRecord = await service.createRecord(record);
      
      // 更新记录
      final updatedRecord = createdRecord.copyWith(
        recordName: '更新后的记录',
        productionCapacity: 2000.0,
      );

      final success = await service.updateRecord(updatedRecord);
      expect(success, isTrue);

      // 验证更新
      final retrievedRecord = await service.getRecordById(createdRecord.id!);
      expect(retrievedRecord!.recordName, '更新后的记录');
      expect(retrievedRecord.productionCapacity, 2000.0);
    });

    test('should delete record (soft delete)', () async {
      // 先创建一个记录
      final record = CarbonFootprintRecord(
        recordCode: '',
        recordName: '待删除记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      final createdRecord = await service.createRecord(record);
      
      // 删除记录
      final success = await service.deleteRecord(createdRecord.id!);
      expect(success, isTrue);

      // 验证记录已被软删除
      final retrievedRecord = await service.getRecordById(createdRecord.id!);
      expect(retrievedRecord, isNull);
    });

    test('should search records', () async {
      // 先创建一个记录
      final record = CarbonFootprintRecord(
        recordCode: '',
        recordName: '搜索测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        location: '北京',
        recordDate: DateTime.now(),
        createdBy: 1,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      await service.createRecord(record);
      
      // 搜索记录
      final searchResults = await service.searchRecords('搜索测试');
      expect(searchResults.length, greaterThan(0));
      expect(searchResults.any((r) => r.recordName.contains('搜索测试')), isTrue);
    });

    test('should get process types', () async {
      final processTypes = await service.getProcessTypes();
      
      expect(processTypes, isA<List<Map<String, dynamic>>>());
      expect(processTypes.length, 4); // 应该有4种工艺类型
      
      // 验证工艺类型数据
      final typeNames = processTypes.map((t) => t['type_name'] as String).toList();
      expect(typeNames, contains('电解水制氢'));
      expect(typeNames, contains('天然气制氢'));
      expect(typeNames, contains('煤制氢'));
      expect(typeNames, contains('生物质制氢'));
    });

    test('should get statistics', () async {
      final statistics = await service.getStatistics();
      
      expect(statistics, isA<Map<String, dynamic>>());
      expect(statistics['total_records'], isA<int>());
      expect(statistics['total_production'], isA<double>());
      expect(statistics['total_energy_consumption'], isA<double>());
      expect(statistics['total_carbon_emission'], isA<double>());
      expect(statistics['process_statistics'], isA<List>());
    });

    test('should validate record data', () {
      final errors = CarbonFootprintService.validateRecordData(
        recordName: '测试记录',
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
        energySource: '太阳能',
        equipmentEfficiency: 85.5,
        operationHours: 8760,
        location: '北京',
        projectPhase: '运行阶段',
      );

      // 验证没有错误
      final hasErrors = errors.values.any((error) => error != null);
      expect(hasErrors, isFalse);
    });

    test('should detect validation errors', () {
      final errors = CarbonFootprintService.validateRecordData(
        recordName: '', // 空名称
        processType: 1,
        productionCapacity: 1000.0,
        energyConsumption: 50000.0,
        carbonEmission: 0.0,
      );

      // 验证有错误
      expect(errors['recordName'], isNotNull);
      expect(errors['recordName'], '记录名称不能为空');
    });
  });
} 